#include <stdlib.h>
#include <stdio.h>

#define ds_mp_c
#define LUA_LIB

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

#include "as_lib9.h"

#include <sys/types.h>
#include <sys/stat.h>

long file_size(const char * filename)  
{
	struct stat st;
	
	if(stat(filename,&st) < 0)
	{
		return false;
	}
	
	return st.st_size;
}

static int mp_init(lua_State* L)
{
	//int mode = (int)luaL_checknumber(L, 1);
	//PA_Init();
	//PA_VBLFunctionInit(AS_SoundVBL);
	AS_Init(AS_MODE_MP3 | AS_MODE_SURROUND | AS_MODE_16CH);
	AS_SetDefaultSettings(AS_PCM_8BIT, 11025, AS_SURROUND);
	//AS_Init(mode);
	//AS_SetDefaultSettings(AS_PCM_8BIT, 11025, AS_SURROUND);
	//PA_InitASLibForMP3(AS_MODE_MP3 | AS_MODE_SURROUND | AS_MODE_8CH);
	return 0;
}

static int mp_play(lua_State* L)
{
	char * file = (char *)luaL_checkstring(L, 1);
	//long size = file_size(file)
	//AS_MP3DirectPlay(file, size);
	AS_MP3StreamPlay(file);
	return 0;
}

static int mp_pause(lua_State* L)
{
	AS_MP3Pause();
	return 0;
}

static int mp_stop(lua_State* L)
{
	AS_MP3Stop();
	return 0;
}

static int mp_unpause(lua_State* L)
{
	AS_MP3Unpause();
	return 0;
}

static int mp_loop(lua_State* L)
{
	bool loop = (bool)lua_toboolean(L, 1);
	AS_SetMP3Loop(loop);
	return 0;
}

static int mp_rate(lua_State* L)
{
	int rate = (int)luaL_checknumber(L, 1);
	AS_SetMP3Rate(rate);
	return 0;
}

static int mp_pan(lua_State* L)
{
	int pan = (int)luaL_checknumber(L, 1);
	AS_SetMP3Pan(pan);
	return 0;
}

static int mp_delay(lua_State* L)
{
	int delay = (int)luaL_checknumber(L, 1);
	AS_SetMP3Delay(delay);
	return 0;
}

static int mp_setDefaultSettings(lua_State* L)
{
	int format = (int)luaL_checknumber(L, 1);
	int rate = (int)luaL_checknumber(L, 2);
	int delay = (int)luaL_checknumber(L, 3);
	AS_SetDefaultSettings(format, rate, delay);
	return 0;
}

static int mp_getStatus(lua_State* L)
{
	int status = AS_GetMP3Status();
	lua_pushnumber(L, status);	
	return 1;
}

static const luaL_Reg mplib [] = {
   {"init", mp_init},
   {"play", mp_play},
   {"pause", mp_pause},
   {"stop", mp_stop},
   {"unpause", mp_unpause},
   {"loop", mp_loop},
   {"rate", mp_rate},
   {"pan", mp_pan},
   {"delay", mp_delay},
   {"setDefaultSettings", mp_setDefaultSettings},
   {"getStatus", mp_getStatus},
   {NULL, NULL}
};

/*
** Open infos library
*/
LUALIB_API int luaopen_mp(lua_State* L)
{
   luaL_register(L, LUA_MPLIBNAME, mplib);
   return 1;
}
